package com.victor.netty.thirdexample;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Created by DJJ on 2019/5/31.
 *
 * 自己上线不会通知自己
 * a,b,c
 * 需求:
 *  1, a 上线 ,通知b,c 服务端打印a 上线
 *
 *  2, a 发消息,a 显示为自己发,b,c都接收到a 的消息
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    //收到任意一个客户端发送的方法
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch->{
            if (ch!=channel){
                ch.writeAndFlush(channel.remoteAddress()+" 发送的消息:"+msg+"\n");
            }else {
                ctx.writeAndFlush(" [自己]:"+msg+"\n");
            }
        });

    }

    @Override
    //连接建立
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //获取对应的通道对象
        Channel channel = ctx.channel();
        //遍历已有的连接,通知他们
        channelGroup.writeAndFlush("[服务器]-"+channel.remoteAddress()+" 加入\n");
        //加入保存
        channelGroup.add(channel);

    }

    @Override
    //连接断掉
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //遍历已有的连接,通知他们
        channelGroup.writeAndFlush("[服务器]-"+channel.remoteAddress()+" 离开\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"下线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
